<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use App\Models\DetectList;
use App\Models\DetectTest;

class CheckUserDetect extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:user-detect';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
         //DetectList::truncate();
         User::query()->where('user_level',">",0)->where('vip_expired_at',">",Carbon::now())->where("upgrade_at","<",Carbon::now())->chunk(50, function (Collection $users) {

            if ($users->isEmpty()) return false;

            /**
             * @var User $user
             */
            
            foreach ($users as $user) {
                $isExists = $user->white()->where('is_always',1)->exists();
                $isTemp = $user->white()->where('is_always',0)->where('expired_at',">",Carbon::now())->exists(); 
                if($isExists || $isTemp){

                    continue;
                }


               /*$childrenOrderCount = $user->myVipChildren()->join('orders', 'orders.user_id','users.id')->whereNotNull('orders.paid_at')->distinct('user_id')->count();*/

               if($user->myStarChildrenCount() <= $user->user_level ){
                    $user->detect()->create();
               }



             }

            return true;

        });
    }
}
